package per.ace.validate.config;

import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @program: springbootDemo
 * @description: controller 增强处理器
 * @author: ace
 * @Date: 2020-06-12 14:05
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    /**
     * 在哪里进行拦截
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        final String returnTypeName = methodParameter.getParameterType().getName();
        return !"per.ace.validate.config.GlobalResponse".equals(returnTypeName)
                && !"org.springframework.http.ResponseEntity".equals(returnTypeName);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        final String returnTypeName = methodParameter.getParameterType().getName();
        if("void".equals(returnTypeName)){
            return GlobalResponse.success(null);
        }
        //返回是不是json类型
        if(!mediaType.includes(MediaType.APPLICATION_JSON)){
            return o;
        }
        if("per.ace.validate.config.GlobalResponse".equals(returnTypeName)){
            return o;
        }
        return GlobalResponse.success(o);
    }


    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({DemoException.class})
    public <T> GlobalResponse<T> handlerException(DemoException exception){
        log.error(Throwables.getStackTraceAsString(exception));
       return GlobalResponse.fail(exception.getErrorMsg(),exception.getErrorCode());

    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({Throwable.class})
    public <T> GlobalResponse<T> handlerThrowable(Throwable throwable){
        log.error(Throwables.getStackTraceAsString(throwable));
        return GlobalResponse.fail(Throwables.getStackTraceAsString(throwable),null);
    }
}
